package com.seven.web;

import com.seven.db.Database;
import com.seven.service.SendEMailService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * 加入了rabbitmq队列
 * @Author seven
 * @Date 2020/5/11 16:19
 **/
@RestController
public class SendQueueController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private long start=0L;

    @GetMapping("queue/register")
    public String register(String name,String email){
         start = System.currentTimeMillis();
        if (name!=null){
            //加入队列
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("email",email);
            stringStringHashMap.put("name",name);
            rabbitTemplate.convertAndSend("amqpAdmin.first","amqpAdmin.routingkey",stringStringHashMap);
            Database.save(name);
            System.out.println("耗时："+(System.currentTimeMillis()-start)+"ms");
            return "已经给您发送邮件，请登录邮件激活";
        }
        return "register未知错误";
    }

    @Autowired
    private SendEMailService sendEMailService;
    @RabbitListener(queues = "amqpAdmin.queue")
    public void sendEmail(HashMap<String, String> hashMap){
        String email = hashMap.get("email");
        String name = hashMap.get("name");
        if (email==null||name==null){
            throw new RuntimeException("邮箱密码为空");
        }
        sendEMailService.send(email,name);
        Database.save(name);
        System.out.println("发送完成耗时："+(System.currentTimeMillis()-start)+"ms");
    }
}
